package cn.iocoder.yudao.framework.excel.core.util;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.framework.excel.core.handler.FormulaTotalHandler;
import cn.iocoder.yudao.framework.excel.core.handler.SelectSheetWriteHandler;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * Excel 工具类
 *
 * @author 芋道源码
 */
public class ExcelUtils {

    /**
     * 将列表以 Excel 响应给前端
     *
     * @param response  响应
     * @param filename  文件名
     * @param sheetName Excel sheet 名
     * @param head      Excel head 头
     * @param data      数据列表哦
     * @param <T>       泛型，保证 head 和 data 类型的一致性
     * @throws IOException 写入失败的情况
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 Class<T> head, List<T> data) throws IOException {
        // 输出 Excel
        EasyExcel.write(response.getOutputStream(), head)
                .autoCloseStream(false) // 不要自动关闭，交给 Servlet 自己处理
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 基于 column 长度，自动适配。最大 255 宽度
                .registerWriteHandler(new SelectSheetWriteHandler(head)) // 基于固定 sheet 实现下拉框
                .registerWriteHandler(new FormulaTotalHandler())
                .registerConverter(new LongStringConverter()) // 避免 Long 类型丢失精度
                .sheet(sheetName).doWrite(data);
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + HttpUtils.encodeUtf8(filename));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    }

    public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
        return EasyExcel.read(file.getInputStream(), head, null)
                .autoCloseStream(false)
                .sheet()// 不要自动关闭，交给 Servlet 自己处理
                .doReadSync();
    }



    public static List<Map<String, String>> excelToMap(MultipartFile file) {
        // 用于存储结果的列表
        List<Map<String, String>> result = new ArrayList<>();

        try (InputStream inputStream = file.getInputStream()) {
            // 读取 Excel 文件
            EasyExcel.read(inputStream, new AnalysisEventListener<Map<Integer, String>>() {
                private List<String> headList; // 表头列表
                int count = 0;
                final String key = "坐标集合";

                @Override
                public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                    // 获取表头
                    this.headList = new ArrayList<>(headMap.values());
                }

                @Override
                public void invoke(Map<Integer, String> data, AnalysisContext context) {
                    // 将每一行数据转换为 Map<String, Object>
                    Map<String, String> rowMap = new HashMap<>();
                    String areaName = data.get(0); //区域名
                    if(count == 0 && (areaName ==null || areaName.isEmpty())){
                        throw exception(new ErrorCode(20000, "EXCEL-首条数据区域名称不能为空"));
                    }
                    String list = data.get(2);
                    if(list == null || list.isEmpty()){
                        throw exception(new ErrorCode(200001, "EXCEL-坐标集合不能为空"));
                    }
                    list = list.trim();
                    if(areaName == null){
                        Map<String, String> map = result.get(count-1);
                        String o = String.valueOf(map.get(key));
                        map.put(key,o+list);

                    }else {
                        for (int i = 0; i < headList.size(); i++) {
                            String s1 = data.get(i);
                            if(s1 != null && !s1.isEmpty()){
                                s1 = s1.trim();
                            }
                            rowMap.put(headList.get(i), s1);
                        }
                        result.add(rowMap);
                        count++;
                    }
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    // 读取完成后的操作
                    System.out.println("Excel 文件读取完成");
                }
            }).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException("读取 Excel 文件失败", e);
        }

        return result;
    }

}
